package com.ruoyi.alipay.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.ruoyi.alipay.config.AlipayConfig;
import com.ruoyi.alipay.domain.AlipayOrder;
import com.ruoyi.alipay.service.AlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {

    // 注入AlipayConfig配置类
    @Autowired
    private AlipayConfig alipayConfig;

    /**
     * 创建支付宝订单
     * @param order
     * @return
     */
    @Override
    public String createOrder(AlipayOrder order) {
        try {
            // 获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(
                    alipayConfig.getGatewayUrl(),
                    alipayConfig.getAppId(),
                    alipayConfig.getMerchantPrivateKey(),
                    "json",
                    alipayConfig.getCharset(),
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getSignType());

            // 设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
            alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());

            // 构建订单参数
            String bizContent = "{" +
                    "\"out_trade_no\":\"" + order.getOutTradeNo() + "\"," +
                    "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                    "\"total_amount\":" + order.getTotalAmount() + "," +
                    "\"subject\":\"" + order.getSubject() + "\"," +
                    "\"body\":\"" + order.getBody() + "\"}";
            
            alipayRequest.setBizContent(bizContent);
            
            // 调用SDK生成表单
            return alipayClient.pageExecute(alipayRequest).getBody();
            
        } catch (Exception e) {
            log.error("创建支付宝订单失败", e);
            return null;
        }
    }

    /**
     * 验证支付宝回调签名
     * @param params
     * @return
     */
    @Override
    public boolean verifyNotify(Map<String, String> params) {
        try {
            // 打印接收到的所有参数
            log.info("待验签的参数：{}", params);
            
            // 获取签名
            String sign = params.get("sign");
            if (sign == null) {
                log.error("签名为空");
                return false;
            }

            // 获取待验签的内容
            String content = AlipaySignature.getSignCheckContentV1(params);
            log.info("待验签内容：{}", content);

            // 验证签名
            boolean result = AlipaySignature.rsa256CheckContent(content, sign, 
                alipayConfig.getAlipayPublicKey(), "UTF-8");
            
            log.info("验签结果：{}", result);
            return result;
        } catch (Exception e) {
            log.error("验证支付宝回调签名失败", e);
            return false;
        }
    }
} 